package controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import models.BackInfo;
import models.Operator;
import services.AuthorityService;
import services.BackInfoService;
import services.DeviceService;
import utils.BizConstants;
import utils.ExcelUtil;
import utils.FileConfig;
import vos.BackInfoSearchVo;
import vos.BackInfoVo;
import vos.CountMonthVo;
import vos.DeviceVo;
import vos.ReturnCode;
import vos.ReturnListVo;

/**
 * 财务管理->返款信息
 * 
 * @ClassName: BackInfoController 
 * @author: wangsm
 * @date: 2016年5月24日 上午9:53:34
 */
public class BackInfoController extends BaseController {
	/**
	 * 
	 * 返款信息
	 *
	 * @Title: backinfo 
	 * @return: void
	 */
	public static void backinfo(String menuid){
		Operator oper=getLoginUser();
		List<String> auths=AuthorityService.getAuthorityByOperAndMenu(menuid,oper.operatorid);
		for(String auth : auths){
			renderArgs.put(auth, auth);
		}
		render();
	}
	/**
	 * 获取返款信息列表
	 *
	 * @Title: getBackInfo 
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param backbegintime
	 * @param backendtime
	 * @param countbegintime
	 * @param countendtime
	 * @param dealerid
	 * @param dealername
	 * @param isback
	 * @param isreject
	 * @return: void
	 */
	public static void getBackInfo(int page,int rows, String sort,String order,
			String backbegintime,String backendtime,String countbegintime,String countendtime,
			String dealerid,String dealername,Boolean isback,Boolean isreject,String shopid,String shopname ){
		if(page==0){
			page=1;
		}
		if(rows==0){
			rows=BizConstants.pagesize;
		}
		BackInfoSearchVo vo=new BackInfoSearchVo(page,rows,sort,order,
				backbegintime,backendtime,countbegintime,countendtime,
				dealerid,dealername,isback,isreject,shopid,shopname);
		long total=BackInfoService.countBackInfo(vo);
		ReturnListVo listVo=new ReturnListVo();
		listVo.setTotal(total);
		List<BackInfoVo> lists=BackInfoService.listBackInfo(vo);
		listVo.setRows(lists);
		renderJSON(listVo);
	}
	/**
	 * 批量设置返款（按照统计金额进行返款）
	 *
	 * @Title: betchBack 
	 * @param ids 返款信息id
	 * @return: void
	 */
	public static void betchBack(String ids){
		if(!checkAuthority("BACKINFO_ENABLE")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode,"未选中记录");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		List<BackInfoVo> lists=BackInfoService.getByIds(listid);
		if(lists==null||lists.size()<=0){
			renderFailedJson(ReturnCode.ErrorCode,"记录信息不存在");
		}
		for(int i=0;i<lists.size();i++){
			if(lists.get(i).isback){
				renderFailedJson(ReturnCode.ErrorCode,"记录中包含已返款,经销商为："+lists.get(i).dealername);
				break;
			}
			if(lists.get(i).isreject){
				renderFailedJson(ReturnCode.ErrorCode,"记录已驳回,经销商为："+lists.get(i).dealername);
				break;
			}
		}
		Operator oper=getLoginUser();
		boolean issuccess=BackInfoService.betchBack(listid,oper.operatorid);
		if(issuccess){
			renderFailedJson(ReturnCode.SuccessCode,"返款成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"返款失败");
		}
	}
	/**
	 * 编辑返款信息
	 *
	 * @Title: editBackInfo 
	 * @return: void
	 */
	public static void backInfoEdit(Long id){
		BackInfoVo backInfo=BackInfoService.getById(id);
		renderArgs.put("backinfo", backInfo);
		render();
	}
	/**
	 * 更新返款信息
	 *
	 * @Title: updateBackInfo 
	 * @param backinfo
	 * @return: void
	 */
	public static void updateBackInfo(BackInfo backinfo){
		if(!checkAuthority("BACKINFO_EDIT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(backinfo==null){
			renderFailedJson(ReturnCode.ErrorCode,"返款信息不能为空");
		}
		if(backinfo.id==null){
			renderFailedJson(ReturnCode.ErrorCode,"返款信息不存在");
		}
		if(backinfo.backtotal==null){
			renderFailedJson(ReturnCode.ErrorCode,"返款金额不能为空");
		}
		if(backinfo.backtotal>backinfo.counttotal){
			renderFailedJson(ReturnCode.ErrorCode,"返款金额不可大于统计金额");
		}
		if(backinfo.backtotal<backinfo.counttotal&&StringUtils.isEmpty(backinfo.reason)){
			renderFailedJson(ReturnCode.ErrorCode,"小于统计金额时请录入原因");
		}
		if(backinfo.backtotal.equals(backinfo.counttotal)){
			backinfo.reason="";
		}
		if(backinfo.remark.length()>255){
			renderFailedJson(ReturnCode.ErrorCode,"备注长度不可大于255");
		}
		BackInfoVo back=BackInfoService.getById(backinfo.id);
		if(back.isback){
			renderFailedJson(ReturnCode.ErrorCode,"该记录已返款");
		}
		if(back.isreject){
			renderFailedJson(ReturnCode.ErrorCode,"该记录已驳回");
		}
		Operator oper=getLoginUser();
		boolean issuccess=BackInfoService.updateBackInfo(backinfo,oper.operatorid);
		if(issuccess){
			renderFailedJson(ReturnCode.SuccessCode,"修改成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"修改失败");
		}
	}
	/**
	 * 查看返款信息详情
	 *
	 * @Title: viewBackInfo 
	 * @return: void
	 */
	public static void viewBackInfo(Long id){
		if(!checkAuthority("BACKINFO_EDIT")){
			render("errors/404.html");
		}
		BackInfoVo backInfo=BackInfoService.getById(id);
		renderArgs.put("backinfo", backInfo);
		render();
	}
	/**
	 * 批量驳回
	 *
	 * @Title: betchReject 
	 * @param ids
	 * @return: void
	 */
	public static void betchReject(String ids,String rejreason){
		if(!checkAuthority("BACKINFO_BETCHREJECT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(StringUtils.isEmpty(ids)){
			renderFailedJson(ReturnCode.ErrorCode, "选中记录为空");
		}
		if(StringUtils.isEmpty(rejreason)){
			renderFailedJson(ReturnCode.ErrorCode, "驳回信息不能为空");
		}
		String[] id=ids.split(",");
		List<String> listid=new ArrayList<String>();
		Collections.addAll(listid, id);
		List<BackInfoVo> lists=BackInfoService.getByIds(listid);
		if(lists==null||lists.size()<=0){
			renderFailedJson(ReturnCode.ErrorCode,"记录信息不存在");
		}
		for(int i=0;i<lists.size();i++){
			if(lists.get(i).isback){
				renderFailedJson(ReturnCode.ErrorCode,"记录中包含已返款,经销商为："+lists.get(i).dealername);
				break;
			}
			//判断是否存在下个月未驳回
			BackInfoVo bback=BackInfoService.getFData(lists.get(i).shopid,lists.get(i).cmonth);
			if(bback!=null&&bback.isreject==false){
				boolean iscontain=false;
				for(int j=0;j<lists.size();j++){
					if(lists.get(j).shopid.equals(bback.shopid)&&lists.get(j).cmonth.equals(bback.cmonth)){
						iscontain=true;
						break;
					}
				}
				if(!iscontain){
					renderFailedJson(ReturnCode.ErrorCode, "后一个月的数据已存在,且未驳回");
				}
			}
		}
		Operator oper=getLoginUser();
		boolean issuccess=BackInfoService.betchReject(listid,oper.operatorid,rejreason);
		if(issuccess){
			renderFailedJson(ReturnCode.SuccessCode,"驳回成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"驳回失败");
		}
	}
	/**
	 * 驳回
	 *
	 * @Title: reject 
	 * @param id 记录id
	 * @param rejreason 驳回原因
	 * @return: void
	 */
	public static void reject(Long id,String rejreason){
		if(!checkAuthority("BACKINFO_REJECT")){
			renderFailedJson(ReturnCode.ErrorCode, "您没有操作权限，请联系管理员");
		}
		if(id==null){
			renderFailedJson(ReturnCode.ErrorCode, "选中的记录不能为空");
		}
		if(StringUtils.isEmpty(rejreason)){
			renderFailedJson(ReturnCode.ErrorCode, "驳回原因不能为空");
		}
		BackInfoVo back=BackInfoService.getById(id);
		if(back==null){
			renderFailedJson(ReturnCode.ErrorCode, "记录不存在");
		}
		if(back.isback){
			renderFailedJson(ReturnCode.ErrorCode, "该记录已返款");
		}
		BackInfoVo bback=BackInfoService.getFData(back.shopid,back.cmonth);
		if(bback!=null){
			renderFailedJson(ReturnCode.ErrorCode, "后一个月的数据已存在,且未驳回");
		}
		Operator oper=getLoginUser();
		boolean issuccess=BackInfoService.reject(id,oper.operatorid,rejreason);
		if(issuccess){
			renderFailedJson(ReturnCode.SuccessCode,"驳回成功");
		}
		else{
			renderFailedJson(ReturnCode.ErrorCode,"驳回失败");
		}
	}
	/**
	 * 导出excel
	 *
	 * @Title: getBackInfo 
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param backbegintime 返款开始时间
	 * @param backendtime 返款结束时间
	 * @param countbegintime 统计开始时间
	 * @param countendtime 统计结束时间
	 * @param dealerid 经销商id
	 * @param dealername 经销商名称
	 * @param isback 是否返款
	 * @param isreject 是否驳回
	 * @return: void
	 */
	public static void exportXls(String backbegintime,String backendtime,String countbegintime,String countendtime,
			String dealerid,String dealername,Boolean isback,Boolean isreject,String shopid,String shopname ){
		BackInfoSearchVo vo=new BackInfoSearchVo(backbegintime,backendtime,countbegintime,countendtime,
				dealerid,dealername,isback,isreject,shopid,shopname);
		List<BackInfoVo> lists=BackInfoService.exportXls(vo);
		long y=System.currentTimeMillis();
		String fileName = "返款信息"+y+".csv";
        response.contentType = "application/x-download";
        renderBinary(ExcelUtil.buildExportFile(FileConfig.backinfoXlsTemplate, lists), fileName);
	}
}
